package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.exception.OrderBusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2023/4/25 14:51
 */
@Component
public class BaiduMapUtil {
    @Value("${sky.baidu.apk}")
    private String baiduAppkey;

    @Value("${sky.baidu.geocodingUrl}")
    private String geocodingUrl;

    @Value("${sky.baidu.directionliteUrl}")
    private String directionliteUrl;

    /**
     * 根据地址解析经纬度
     *
     * @param address
     */
    public String geoCoding(String address) {
        //组装地理编码的调用参数
        Map paramsMap = new HashMap();
        paramsMap.put("address", address);
        paramsMap.put("ak", baiduAppkey);
        paramsMap.put("output", "json");

        //发起调用
        String resultJsonStr = HttpClientUtil.doGet(geocodingUrl, paramsMap);
        JSONObject jsonObject = JSON.parseObject(resultJsonStr);
        if (jsonObject.getInteger("status") != 0) {
            throw new OrderBusinessException("地址解析失败");
        }
        //根据结果解析经纬度
        jsonObject = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = jsonObject.getString("lat");
        String lng = jsonObject.getString("lng");

        //经纬度坐标
        String geoStr = lat + "," + lng;
        return geoStr;
    }

    /**
     * 获取两个地理位置之间的距离
     * @param originGeo 起点经纬度
     * @param destGeo 目的地经纬度
     * @return 距离（单位：米）origin
     */
    public Integer geoDistance4Geo(String originGeo,String destGeo) {
        //组装路线规划的调用参数
        Map paramsMap = new HashMap();
        paramsMap.put("origin", originGeo);
        paramsMap.put("destination", destGeo);
        paramsMap.put("ak", baiduAppkey);
        //发起调用
        String resultJsonStr = HttpClientUtil.doGet(directionliteUrl, paramsMap);
        JSONObject jsonObject = JSON.parseObject(resultJsonStr);
        if (jsonObject.getInteger("status") != 0) {
            throw new OrderBusinessException("地址解析失败");
        }
        jsonObject = (JSONObject) jsonObject.getJSONObject("result").getJSONArray("routes").get(0);
        Integer distance = jsonObject.getInteger("distance");
        return distance;
    }

    /**
     * 获取两个地理位置之间的距离
     * @param originAddress 起点地址
     * @param destAddress 目的地地址
     * @return 距离（单位：米）origin
     */
    public Integer geoDistance4Address(String originAddress,String destAddress) {
        String originGeo = this.geoCoding(originAddress);
        String destGeo = this.geoCoding(destAddress);
        Integer distance = geoDistance4Geo(originGeo, destGeo);
        return distance;
    }

}
